package com.tj.jinzao.activity;

import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.Observer;
import com.netease.nimlib.sdk.RequestCallback;
import com.netease.nimlib.sdk.StatusCode;
import com.netease.nimlib.sdk.auth.AuthService;
import com.netease.nimlib.sdk.auth.AuthServiceObserver;
import com.netease.nimlib.sdk.auth.OnlineClient;
import com.tj.jinzao.R;
import com.tj.jinzao.base.AppExit;
import com.tj.jinzao.base.BaseActivity;
import com.tj.jinzao.common.Settings;
import com.tj.jinzao.fragment.LiveFragment;
import com.tj.jinzao.fragment.MainFragment;
import com.tj.jinzao.fragment.MeFragment;
import com.tj.jinzao.fragment.MyMessageFragment;
import com.tj.jinzao.manager.UserManager;
import com.tj.jinzao.utils.ToastUtils;

import java.lang.reflect.Field;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 尽早首页
 * Created by wjy on 2018/12/10.
 */
public class MainActivity extends BaseActivity {

    private RadioButton[] mRadios;
    private FragmentPagerAdapter mPagerAdapter;

    @BindView(R.id.vp_main)
    ViewPager mViewPaper;

    @BindView(R.id.rg_tab_group)
    RadioGroup mRadioGroup;

    private int mPrevPosition = -1;
    private int mPosition = 0;

    private Fragment mCurrentFragment;


    @Override
    public int getLayoutResource() {
        return R.layout.activity_main;
    }


    @OnClick({R.id.rb_tab_1, R.id.rb_tab_2, R.id.rb_tab_4, R.id.rb_tab_5})
    public void clickTab(View view) {
        int position = 0;
        switch (view.getId()) {
            case R.id.rb_tab_1:
                position = 0;
                break;
            case R.id.rb_tab_2:
                position = 1;
                break;
            case R.id.rb_tab_4:
                position = 2;
                break;
            case R.id.rb_tab_5:
                position = 3;
                break;
        }
        if (mPosition != position) mViewPaper.setCurrentItem(position);
    }
    //当有其他端登录时候主动踢掉
    private void initLogin(){
        NIMClient.getService(AuthServiceObserver.class).observeOtherClients(new Observer<List<OnlineClient>>() {
            @Override
            public void onEvent(List<OnlineClient> onlineClients) {
                if(onlineClients==null||onlineClients.size()==0){
                    return;
                }
                for (int i=0;i<onlineClients.size();i++){
                    NIMClient.getService(AuthService.class).kickOtherClient(onlineClients.get(i)).setCallback(new RequestCallback<Void>() {
                        @Override
                        public void onSuccess(Void aVoid) {

                        }

                        @Override
                        public void onFailed(int i) {

                        }

                        @Override
                        public void onException(Throwable throwable) {

                        }
                    });

                }

            }
        },true);

    }

    //监听登录状态
    private void initNim(){
        NIMClient.getService(AuthServiceObserver.class).observeOnlineStatus(
                new Observer<StatusCode>() {
                    public void onEvent(StatusCode status) {
                        Log.i("tag", "User status changed to: " + status);
                        if (status.wontAutoLogin()) {
                            // 被踢出、账号被禁用、密码错误等情况，自动登录失败，需要返回到登录界面进行重新登录操作
                            ToastUtils.showToast(MainActivity.this,"您的账号已在其他地方登录，请重新登录");
                            UserManager.userLogout();
                            Settings.clearUserData(MainActivity.this);
                            startActivity(new Intent(MainActivity.this, LoginActivity.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK));
                        }
                    }
                }, true);

    }

    @Override
    protected void setupView() {
        super.setupView();
        setAdapter();
        mRadios = new RadioButton[4];
        mRadios[0] = findViewById(R.id.rb_tab_1);
        mRadios[1] = findViewById(R.id.rb_tab_2);
        mRadios[2] = findViewById(R.id.rb_tab_4);
        mRadios[3] = findViewById(R.id.rb_tab_5);
        mViewPaper.setOffscreenPageLimit(3);
        initNim();
        initLogin();
    }

    @OnClick(R.id.iv_public)
    void publicDaily() {
        startActivity(new Intent(this, PublishMaskActivity.class));
    }

    public void setAdapter() {
        mPagerAdapter = new FragmentPagerAdapter(getSupportFragmentManager()) {
            @Override
            public Fragment getItem(final int position) {
                switch (position) {
                    case 0:// 首页
                        return MainFragment.newInstance();
                    case 1:// 直播
                        return LiveFragment.newInstance();
                    case 2:// 消息
                        return MyMessageFragment.newInstance();
                    case 3:// 我的
                        return MeFragment.newInstance();
                }
                return null;
            }

            @Override
            public CharSequence getPageTitle(int position) {
                return "";
            }

            @Override
            public int getCount() {
                return 4;
            }


            @Override
            public void setPrimaryItem(ViewGroup container, int position, Object object) {
                super.setPrimaryItem(container, position, object);
                if (object == null || (mPrevPosition == position && mCurrentFragment != null))
                    return;
                mPrevPosition = position;
                mCurrentFragment = (Fragment) object;
                if (null == mCurrentFragment) return;
            }

            @Override
            public void destroyItem(ViewGroup container, int position, Object object) {
                super.destroyItem(container, position, object);
                getSupportFragmentManager().beginTransaction()
                        .remove((Fragment) object).commitAllowingStateLoss();
                try {
                    Field parentFragment = Fragment.class.getDeclaredField("mParentFragment");
                    parentFragment.setAccessible(true);
                    parentFragment.set(object, null);
                } catch (NoSuchFieldException ignored) {
                } catch (IllegalAccessException ignored) {
                }
            }
        };
        mViewPaper.setAdapter(mPagerAdapter);
        mViewPaper.setCurrentItem(mPosition);
        mViewPaper.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int i, float v, int i1) {

            }

            @Override
            public void onPageSelected(int i) {
                mPosition = i;
                mRadios[i].setChecked(true);
            }

            @Override
            public void onPageScrollStateChanged(int i) {

            }
        });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (mCurrentFragment != null)
            mCurrentFragment.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }
    boolean pp = true;
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            ToastUtils.showToast(MainActivity.this, "再按一次退出该程序");
            if (pp) {
                pp = false;
                Timer timer = new Timer();
                TimerTask task = new TimerTask() {

                    @Override
                    public void run() {
                        pp = true;
                    }
                };
                timer.schedule(task, 2000);
            } else {
                AppExit.getInstance().exit();
            }
        }
        return true;

    }

}
